// fenxiao/businSum/index.js
const app = getApp();
const utils = require('../../utils/util.js');
import getUserCard from "../../utils/getUserCard.js";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMoreHidden: 1,
    isAll: 0, //0只有自己，1自己和自己下边的商户所有人的报表
    parentuid: '',
    childUid: '', //某商户报表
    theyear: '',
    themonth: '',
    theday: '',
    weekno: '', //本月第几周
    weektimeTotime: '',
    currentType: 1, //1日报2周报3月报
    selectDate: '',
    selectMonth: '',
    reportInfo: {},
    subEndtime: '',
    nowDate: '',
    showEmployee: false,
    employeeid: 0,
    employeename: '',
    employeeList: [], //所有收银员
    payment: 1, //1自动核销2手动核销
    showPayment: false,
    isMerchant: false, //是否绑定商户
    childType: 1,//2:所有分店
    isMainStore: false
  },

  branchExports: function(){
    wx.redirectTo({
      url: '/pages/branchStore/index?showAll=1&parentUid=' + this.data.parentuid,
    })
  },

  //是否绑定商户，无绑定只显示手动核销，绑定则显示自动核销和手动核销
  showReport: function(childUid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/staff/GetPayStore?uid=' + childUid,
      success: function(res) {
        let isMerchant = false;
        let payment = that.data.payment;
        if (res.data.Code == 0) {
          if (res.data.Data.isWxStore || res.data.Data.isAliStore) {
            isMerchant = true;
          }else{
            payment = 2;
          }
          that.setData({
            isMerchant: isMerchant,
            payment: payment
          })
        }
      }
    })
  },

  // 线上经营报表
  getPayReport: function(endtime, currentType) {
    let that = this;
    let isAll = that.data.isAll;
    let parentuid = 0;
    if(isAll == 1){//所有名下商户的数据
      parentuid = that.data.parentuid;
    }
    let childUid = that.data.childUid;
    if(that.data.childType == 2){
      childUid = app.globalData.myUserInfo.Uid;
      parentuid = app.globalData.myUserInfo.Uid;
    }
    wx.request({
      url: app.globalData.host + '/api/WxStore/GetPayReport',
      data: {
        uid: childUid,
        endtime: endtime,
        timeType: currentType,
        storeId: app.globalData.storeId,
        parentUid: parentuid,
        employeeId: that.data.employeeid,
        isAll: isAll,
        childType: that.data.childType
      },
      method: 'POST',
      success: function(res) {
        if (res.data.Code == 0) {
          let reportInfo = res.data.Data;
          if (currentType == 1) {
            if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney > 0) {
              reportInfo.remark = '与上一日增长';
            } else if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney < 0) {
              reportInfo.remark = '与上一日减少';
            } else {
              reportInfo.remark = '与上一日持平';
            }
          } else if (currentType == 2) {
            if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney > 0) {
              reportInfo.remark = '与上一周增长';
            } else if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney < 0) {
              reportInfo.remark = '与上一周减少';
            } else {
              reportInfo.remark = '与上一周持平';
            }
          } else {
            if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney > 0) {
              reportInfo.remark = '与上一月增长';
            } else if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney < 0) {
              reportInfo.remark = '与上一月减少';
            } else {
              reportInfo.remark = '与上一月持平';
            }
          }

          if (reportInfo.CouponMoney == null) {
            reportInfo.CouponMoney = 0.00;
          }
          if (reportInfo.BeforeSurplusMoney == null) {
            reportInfo.BeforeSurplusMoney = 0.00;
          }
          if (reportInfo.OrderAmount == null) {
            reportInfo.OrderAmount = 0.00;
          }
          if (reportInfo.SurplusMoney == null) {
            reportInfo.SurplusMoney = 0.00;
          }
          that.setData({
            reportInfo: reportInfo
          })
        }
      }
    })
  },
  // 线下经营报表
  getPayReportOffLine: function(endtime, currentType) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/wxstore/GetOffLineReport?uid=' + that.data.childUid + '&endTime=' + endtime + '&timeType=' + currentType + '&parentUid=' + that.data.parentuid + '&employeeid=' + that.data.employeeid + '&isAll=' + that.data.isAll + '&storeId=' + app.globalData.storeId + '&childType=' + that.data.childType,
      success: function(res) {
        if (res.data.Code == 0) {
          let reportInfo = res.data.Data;
          if (currentType == 1) {
            if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney > 0) {
              reportInfo.remark = '与上一日增长';
            } else if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney < 0) {
              reportInfo.remark = '与上一日减少';
            } else {
              reportInfo.remark = '与上一日持平';
            }
          } else if (currentType == 2) {
            if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney > 0) {
              reportInfo.remark = '与上一周增长';
            } else if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney < 0) {
              reportInfo.remark = '与上一周减少';
            } else {
              reportInfo.remark = '与上一周持平';
            }
          } else {
            if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney > 0) {
              reportInfo.remark = '与上一月增长';
            } else if (reportInfo.SurplusMoney - reportInfo.BeforeSurplusMoney < 0) {
              reportInfo.remark = '与上一月减少';
            } else {
              reportInfo.remark = '与上一月持平';
            }
          }

          if (reportInfo.CouponMoney == null) {
            reportInfo.CouponMoney = 0.00;
          }
          if (reportInfo.BeforeSurplusMoney == null) {
            reportInfo.BeforeSurplusMoney = 0.00;
          }
          if (reportInfo.OrderAmount == null) {
            reportInfo.OrderAmount = 0.00;
          }
          if (reportInfo.SurplusMoney == null) {
            reportInfo.SurplusMoney = 0.00;
          }
          that.setData({
            reportInfo: reportInfo
          })
        }
      }
    })
  },
  // 选择收银员
  selectEmploy: function() {
    let that = this;
    that.setData({
      showEmployee: !that.data.showEmployee
    })
    that.getEmployeeListByUid();
  },
  getEmployeeListByUid: function(){
    let that = this;
    let childuid = that.data.childUid;
    if (childuid) {
      wx.request({
        url: app.globalData.host + '/api/wxstore/GetEmployeeListByUid?createuid=' + childuid + '&page=' + that.data.CurrentPage,
        success: function(res) {
          if (res.data.Code == 0) {
            let employeeList = [];
            let loadingMoreHidden = 1;
            if (res.data.Data) {
              employeeList = res.data.Data.Items;
              loadingMoreHidden = res.data.Data.TotalPages;
            }
            if(that.data.CurrentPage != 1){
              var preGoods = that.data.employeeList;
              employeeList = preGoods.concat(employeeList);
            }
            that.setData({
              employeeList: employeeList,
              loadingMoreHidden: loadingMoreHidden
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.Message,
              showCancel: false
            })
          }
        }
      })
    }
  },

  bindscroll: function(e){
    let scrollTop = e.detail.scrollTop
    if(scrollTop > 0){
      if(this.data.CurrentPage < this.data.loadingMoreHidden ){
        this.data.CurrentPage += 1; 
        this.getEmployeeListByUid();
      }
    }
  },

  togetEmployeeReport: function(e) {
    let employeeid = e.currentTarget.dataset.employeeid;
    let employeename = e.currentTarget.dataset.employeename;
    this.setData({
      employeeid: employeeid,
      employeename: employeename,
      showEmployee: !this.data.showEmployee
    })
    if (this.data.payment == 1) {
      this.getPayReport(this.data.subEndtime, this.data.currentType);
    } else {
      this.getPayReportOffLine(this.data.subEndtime, this.data.currentType);
    }
  },
  // 选择核销方式
  selectPayment: function() {
    let that = this;
    that.setData({
      showPayment: !that.data.showPayment,
    })
  },
  togetEmployeeReport2: function(e) { //手动核销
    let payment = e.currentTarget.dataset.payment;
    this.setData({
      payment: payment,
      showPayment: !this.data.showPayment
    })
    this.getPayReportOffLine(this.data.subEndtime, this.data.currentType)
  },
  togetEmployeeReport3: function(e) { //自动核销
    let payment = e.currentTarget.dataset.payment;
    this.setData({
      payment: payment,
      showPayment: !this.data.showPayment
    })
    this.getPayReport(this.data.subEndtime, this.data.currentType);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var clock = year + "年";
    if (month < 10)
      clock += "0";
    clock += month + "月";
    if (day < 10)
      clock += "0";
    clock += day + "日";
    let subEndTime = year + '-' + month + '-' + day;
    let nowDate = subEndTime;
    let selectMonth = year + '年' + month + '月';
    if(options.childType){
      that.data.childType = options.childType;
    }
    let isAll = 0;
    let parentuid = '';
    let childUid = '';
    let payment = 1; //1自动核销2手动核销
    let employeeid = 0;
    let employeename = '';
    that.getAiCardInfo();
    if (options.childUid) {
      childUid = options.childUid
      that.showReport(childUid);
    }
    if(options.isAll){
      isAll = options.isAll
    }
    if(options.parentuid){
      parentuid = options.parentuid
    }
    if (options.payment) {
      payment = options.payment;
    }
    if (options.employeeid) {
      employeeid = options.employeeid
    }
    if (options.employeename) {
      employeename = options.employeename;
    }
    that.setData({
      isAll: isAll,
      childUid: childUid,
      parentuid: parentuid,
      payment: payment,
      employeeid: employeeid,
      employeename: employeename
    })
    
    if (options.selectWeek) {
      let week = options.selectWeek.substr(6, 2) + '-' + options.selectWeek.substr(9, 2);
      subEndTime = year + '-' + week;
      month = options.month;
      that.setData({
        currentType: 2,
        weekno: options.weekno,
        weektimeTotime: options.selectWeek
      })
      setTimeout(function() {
        if (that.data.payment == 1) { //线上核销
          that.getPayReport(subEndTime, 2);
        } else { //线下核销
          that.getPayReportOffLine(subEndTime, 2);
        }
      }, 500);
    } else {
      if (that.data.payment == 1) { //线上核销
        that.getPayReport(subEndTime, that.data.currentType);
      } else { //线下核销
        that.getPayReportOffLine(subEndTime, that.data.currentType);
      }
    }
    that.setData({
      nowDate: nowDate,
      subEndtime: subEndTime,
      selectDate: clock,
      selectMonth: selectMonth,
      theyear: year,
      themonth: month,
      theday: day
    })
  },

  getAiCardInfo: function(){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.userInfo.Uid,
      success: function(res){
        if(res.data.Code == 0){
          if(res.data.Data){
            if(res.data.Data.ParentUid == 0){
              that.setData({
                isMainStore: true
              })
            }
          }
        }
      },
    })
  },
  // 收款码（不要随意改）
  toMyPayCode: function() {
    let uid = this.data.childUid;
    getUserCard(uid, function(cardid) {
      wx.navigateTo({
        url: '/pages/weijieke/myPayCode/index?staffid=' + cardid + '&employeeid=0'
      })
    })
  },

  // 导出经营报表
  toExports: function() {
    wx.navigateTo({
      url: '/merchant/merchants/exportRecords/index?parentUid=' + this.data.parentuid + '&childUid=' + this.data.childUid + '&linetype=' + this.data.payment,
    })
  },
  //订单列表
  toWasteAccount: function(e) {
    let that = this;
    let iscoupon = e.currentTarget.dataset.iscoupon;
    let paytype = '';
    if (e.currentTarget.dataset.paytype) {
      paytype = e.currentTarget.dataset.paytype;
    }
    wx.navigateTo({
      url: '/merchant/merchants/wasteAccount/index?iscoupon=' + iscoupon + '&childUid=' + this.data.childUid + '&timeType=' + this.data.currentType + '&endtime=' + this.data.subEndtime + '&paytype=' + paytype + '&employeeid=' + this.data.employeeid + '&isAll=' + this.data.isAll + '&linetype=' + that.data.payment + '&childType=' + this.data.childType
    })
  },

  // 选择报表类型
  changeType: function(e) {
    let that = this;
    let type = e.currentTarget.dataset.type;
    let subEndTime = that.data.subEndtime;
    if (type == 2) {
      var weekday = new Date().getDay(); //获取该日是星期几，0代表星期日
      // 本月第几周
      // var weekno = Math.ceil((that.data.theday + 6 - weekday) / 7);
      var weekno = that.getWeekStr();
      that.allWeeks(weekno);
      that.setData({
        weekno: weekno
      })
    } else {
      if (type == 1) {
        subEndTime = that.data.nowDate;
      }
      if (type == 3) {
        let selectMonth = that.data.selectMonth;
        subEndTime = that.data.nowDate;
      }
      if (that.data.payment == 1) { //线上核销
        that.getPayReport(subEndTime, type);
      } else { //线下核销
        that.getPayReportOffLine(subEndTime, type);
      }

      that.setData({
        subEndtime: subEndTime
      })
    }
    that.setData({
      currentType: type
    })
  },
  
  getWeekStr: function() {
    // 将字符串转为标准时间格式
    let date = new Date();
    let month = date.getMonth() + 1;
    let week = this.getWeekFromDate(date);
    if (week === 0) { //第0周归于上月的最后一周
      month = date.getMonth();
      let dayLast = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
      let timestamp = new Date(new Date().getFullYear(), new Date().getMonth() - 1, dayLast);
      week = this.getWeekFromDate(new Date(timestamp));
    }
    let time = week;
    return time;
  },

  getWeekFromDate: function(date) {
    // 将字符串转为标准时间格式
    let w = date.getDay(); //周几
    if (w === 0) {
      w = 7;
    }
    let week = Math.ceil((date.getDate() + 6 - w) / 7) - 1;
    return week;
  },
  //日期(日报)
  bindDateChange: function(e) {
    var date = e.detail.value;
    if (this.data.payment == 1) { //线上核销
      this.getPayReport(date, 1);
    } else { //线下核销
      this.getPayReportOffLine(date, 1);
    }
    var newdate = date.substr(0, 4) + '年' + date.substr(5, 2) + '月' + date.substr(8, 2) + '日';
    // var newSubtime = date.substr(0, 4) + '-' + date.substr(5, 2) + '-' + date.substr(8, 2);
    this.setData({
      selectDate: newdate,
      subEndtime: date
    })
  },
  //选择第几周：
  selectWeek: function() {
    wx.redirectTo({
      url: '/merchant/merchants/selectWeek/index?childUid=' + this.data.childUid + '&parentuid=' + this.data.parentuid + '&isAll=' + this.data.isAll + '&payment=' + this.data.payment + '&employeeid=' + this.data.employeeid + '&employeename=' + this.data.employeename + '&childType=' + this.data.childType,
    })
  },
  //月报
  bindMonthChange: function(e) {
    let subEndTime = e.detail.value;
    if (this.data.payment == 1) { //线上核销
      this.getPayReport(subEndTime, 3);
    } else { //线下核销
      this.getPayReportOffLine(subEndTime, 3);
    }
    let newMonth = subEndTime.substr(0, 4) + '年' + subEndTime.substr(5, 2) + '月'
    this.setData({
      selectMonth: newMonth,
      subEndtime: subEndTime
    })
  },
  allWeeks: function(weekno) {
    var weekarry = [];
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth();
    var start = new Date(year, month, 1); //当前月第一天的日期
    var end = new Date(year, month + 1, 0); //当前月最后一天的日期
    var start_day = start.getDay();
    let i = 0;
    switch (start_day) {
      case 0:
        i = 0 + 2;
        break;
      case 1:
        i = 1;
        break;
      case 2:
        i = 0 + 7;
        break;
      case 3:
        i = 0 + 6;
        break;
      case 4:
        i = 0 + 5;
        break;
      case 5:
        i = 0 + 4;
        break;
      case 6:
        i = 0 + 3;
        break;
    }
    while (new Date(year, month, i) <= end) {
      weekarry.push([new Date(year, month, i), new Date(year, month, i + 6)]);
      i += 7;
    }
    let weektimeTotime = weekarry[weekno - 1];
    let startTime = utils.formatTime(weektimeTotime[0]).replace(/\//g, ".").substr(5, 5);
    let endTime = utils.formatTime(weektimeTotime[1]).replace(/\//g, ".").substr(5, 5);
    let subEndtime = utils.formatTime(weektimeTotime[1]).replace(/\//g, "-").substr(0, 10);
    if (this.data.payment == 1) { //线上核销
      this.getPayReport(subEndtime, 2);
    } else { //线下核销
      this.getPayReportOffLine(subEndtime, 2);
    }
    this.setData({
      weektimeTotime: startTime + '-' + endTime,
      subEndtime: subEndtime
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  }
})